<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属站点" prop="mixingStationNumber">
          <el-select v-model="queryParams.mixingStationNumber" placeholder="请选择所属站点" clearable class="!w-220px">
            <el-option v-for="(item, index) in mixingStationOptions" :key="index" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>

        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>

        <el-form-item label="客户编号" prop="customerCode">
          <el-input v-model="queryParams.customerCode" placeholder="请输入客户编号" clearable />
        </el-form-item>

        <el-form-item label="是否设置围栏" prop="railStatus">
          <el-select v-model="queryParams.railStatus" placeholder="请选择是否设置围栏" clearable class="!w-220px">
            <el-option v-for="(item, index) in setRailMarkOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="启用状态" prop="customerStatus">
          <el-select v-model="queryParams.customerStatus" placeholder="请选择启用状态" clearable class="!w-220px">
            <el-option v-for="(item, index) in customerStatusOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间区间" prop="timeType">
          <el-select v-model="queryParams.timeType" class="!w-220px">
            <el-option v-for="(item, index) in dateTypeOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item prop="startTime">
          <date-picker v-model:start="queryParams.startTime" v-model:end="queryParams.endTime" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex-x-b">
          <el-button type="success" @click="handleOpenDialog()">
            <template #icon><ep-Plus /></template>
            新增
          </el-button>
          <el-button class="ml-3" @click="handleExport">
            <template #icon><ep-Download /></template>
            导出
          </el-button>
        </div>
      </template>

      <el-table v-auto-h v-loading="loading" :data="tableData" border>
        <el-table-column label="客户名称" width="200" align="center" prop="customerName" />
        <el-table-column label="客户编号" width="100" align="center" prop="customerCode" />
        <el-table-column label="项目名称" min-width="200" align="center" prop="projectName" />
        <el-table-column label="所属站点" min-width="200" align="center" prop="mixingStationName" />
        <el-table-column label="是否设置围栏" width="110" align="center" prop="railStatus">
          <template #default="{ row }">
            {{ setRailMarkOptions.find(item => item.value === row.railStatus)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="启用状态" width="100" align="center" prop="customerStatus">
          <template #default="{ row }">
            <el-tag :type="row.customerStatus === customerStatusOptions[0].value ? 'success' : 'info'">
              {{ customerStatusOptions.find(item => item.value === row.customerStatus)?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新人" width="110" align="center" prop="updateBy" />
        <el-table-column label="更新时间" width="180" align="center" prop="updateTime" />
        <el-table-column label="创建人" width="110" align="center" prop="createBy" />
        <el-table-column label="创建时间" width="180" align="center" prop="createTime" />

        <el-table-column fixed="right" label="操作" width="160" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleSetFence(row)">
              <template #icon><ep-Setting /></template>
              围栏设置
            </el-button>
            <el-button type="primary" link size="small" @click="handleOpenDialog(row)">
              <template #icon><ep-Edit /></template>
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="current" v-model:pagesize="pageSize" :total="total" />
    </el-card>

    <!-- 添加/编辑表单弹框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="customerCode">
          <el-select
            v-model="formData.customerCode"
            filterable
            remote
            placeholder="请选择客户名称"
            :loading="customerLoading"
            :remote-method="(query: string) => fetchCustomerList(query)"
            @change="handleSelectCustomer"
          >
            <el-option v-for="item in customerOptions" :key="item.id" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>

        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
        </el-form-item>

        <el-form-item label="所属站点" prop="mixingStationNumber">
          <el-select v-model="formData.mixingStationNumber" placeholder="请选择所属站点">
            <el-option v-for="item in mixingStationOptions" :key="item.number" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>

        <el-form-item label="启用状态" prop="customerStatus" size="large">
          <el-switch
            v-model="formData.customerStatus"
            size="large"
            inline-prompt
            :active-text="customerStatusOptions[0].label"
            :inactive-text="customerStatusOptions[1].label"
            :active-value="customerStatusOptions[0].value"
            :inactive-value="customerStatusOptions[1].value"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 围栏设置弹框 -->
    <SetFenceDialog v-model="setFenceDialog" :row-data="currentRowData" :business-type="1" @fetch-data="handleQuery" />
  </div>
</template>

<script lang="ts" setup>
import { useRequest, usePagination } from '@/hooks/useRequest'
import type { FormInstance } from 'element-plus'
import { setRailMarkOptions, dateTypeOptions, customerStatusOptions } from './options'
import { getPage, exportPage, addOrUpdate, getMixingStationList, getCustomerList, type MixingStationData } from '@/api/customer/customer'
import type { CustomerPageQuery, Data, Form } from '@/api/customer/customer'

import Storage from '@/utils/Storage'
import { DEFAULT_MIXING_STATION_ID_KEY } from '@/utils/constant'

const queryFormRef = ref<FormInstance>()

const queryParams = reactive<CustomerPageQuery>({ nowPage: 1, pageSize: 10, timeType: 1 })

const { data, loading, run, total, current, pageSize } = usePagination(getPage, { defaultParams: [queryParams], manual: true })

const tableData = computed(() => data.value?.result.records || [])

const handleQuery = () => {
  run(queryParams)
}

const handleResetQuery = () => {
  queryFormRef.value!.resetFields()
  queryParams.endTime = undefined
  handleQuery()
}

const handleExport = () => {
  exportPage(queryParams)
}

// 获取搅拌站下拉数据
const { data: mixingStationData } = useRequest(getMixingStationList, {
  onSuccess({ result }) {
    if (result && result.length) {
      let defaultMixingStation: MixingStationData = null
      const defaultMixingStationId = Storage.getStorage(DEFAULT_MIXING_STATION_ID_KEY)

      // 先从本地缓存匹配搅拌站数据；如果能找到数据，则说明该用户有本地缓存搅拌站的权限
      if (defaultMixingStationId) {
        defaultMixingStation = result.find(item => item.id === defaultMixingStationId)
      }

      // 如果无缓存或者无法匹配到数据；则默认取第一个数据并重新设置缓存
      if (!defaultMixingStation) {
        defaultMixingStation = result[0]
        Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, defaultMixingStation.id)
      }

      queryParams.mixingStationNumber = defaultMixingStation.number
    }
  },
  onAfter() {
    handleQuery()
  }
})
const mixingStationOptions = computed(() => mixingStationData.value?.result || [])

/** --------------------- 添加编辑部分 -------------------- */
const dialog = reactive({
  title: '',
  visible: false
})

const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive<Form>({ customerStatus: 1 })

const rules = reactive({
  customerCode: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  mixingStationNumber: [{ required: true, message: '请选择所属站点', trigger: 'change' }]
})

const handleOpenDialog = async (row?: Data) => {
  dialog.visible = true
  if (row) {
    dialog.title = '编辑客户信息'
    await fetchCustomerList(row.customerName)
    Object.assign(formData, row)
  } else {
    dialog.title = '新增客户信息'
  }
}

const handleCloseDialog = () => {
  dialog.visible = false
  formRef.value.resetFields()
  formData.id = undefined
}

// 获取客户名称下拉数据
const { run: fetchCustomerList, data: customerData, loading: customerLoading } = useRequest(getCustomerList, { manual: true })
const customerOptions = computed(() => customerData.value?.result || [])

// 选择客户名称
const handleSelectCustomer = (code: string) => {
  formData.customerName = customerOptions.value.find(item => item.code === code)?.name
  console.log(formData.customerName)
}

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitLoading.value = true
      addOrUpdate(formData)
        .then(() => {
          ElMessage.success(formData.id ? '修改成功' : '新增成功')
          handleCloseDialog()
          handleQuery()
        })
        .finally(() => (submitLoading.value = false))
    }
  })
}

/** --------------------- 围栏设置部分 -------------------- */
const setFenceDialog = ref(false)
const currentRowData = ref<Data>({})

const handleSetFence = (row: Data) => {
  setFenceDialog.value = true
  currentRowData.value = row
}
</script>
<style lang="scss" scoped></style>
